package cn.yili12.business.mq;


import cn.yili12.business.mq.bean.Message;
import cn.yili12.business.mq.bean.MessageType;
import cn.yili12.business.mq.handler.BaseHandler;
import cn.yili12.business.service.MessageService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.command.ActiveMQMessage;
import org.apache.activemq.command.ActiveMQTextMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

import javax.jms.JMSException;
import javax.jms.Session;

@Component
@Slf4j
public class QueueConsumer {
    @Autowired
    private ApplicationContext applicationContext;

    //    @JmsListener(destination = "${activemq.first.queue:test}")
    @JmsListener(destination = "${activemq.queue:db-queue}", containerFactory = "jmsQueueListener")
    public void consumer(ActiveMQMessage message, Session session) throws JMSException {
        log.info("接收到业务系统消息，ACK_MODE={},开启事务={}，真是类型={}", new Object[]{session.getAcknowledgeMode(), session.getTransacted(), message.getClass().getName()});
        ActiveMQTextMessage textMessage = (ActiveMQTextMessage) message;
        log.info("接受队列消息，内容为：{}", textMessage.getText());
        Message msg = null;
        try {
            JSONObject jsonObject = JSON.parseObject(textMessage.getText());
            msg = JSON.toJavaObject(jsonObject, Message.class);
            if (msg == null || msg.getType() == null) {
                log.warn("报文格式不对，自动接收删除报文");
                message.acknowledge();
                return;
            }
        } catch (Exception e) {
            log.error("解析客服端报文失败", e);
            message.acknowledge();
        }
        try {
            MessageType type = msg.getType();
            BaseHandler baseHandler = (BaseHandler) applicationContext.getBean(type.getHandlerClass());
            baseHandler.handler(msg);
            message.acknowledge();
        } catch (Exception e) {
            log.error("执行业务操作失败", e);
            session.recover();// 此不可省略 重发信息使用
        }
    }
}
